const dgram = require("dgram");
const fs = require("node:fs");
const path = require("node:path");

const server = dgram.createSocket("udp4");

const resolvePath = path.resolve("udp.txt");

// fs.readFile(resolvePath, "utf8", (err, res) => {
//   if (err) {
//     new Error("查找文件错误！");
//   }
//   if (res) {
//   }
// });

server.on("error", (err) => {
  console.log(`错误信息:\n${err.stack}`);
  server.close();
});

server.on("message", (msg, rinfo) => {
  const data = `来自${rinfo.address}:${rinfo.port}的信息: ${msg}`;
  console.log(`来自${rinfo.address}:${rinfo.port}的信息: ${msg}`);
  fs.appendFile(resolvePath, data);
});

server.on("listening", () => {
  const address = server.address();
  //   console.log(
  //     `发送信息地址${address.address}:${address.port}发送的消息: ${message}`
  //   );
});

let prot = 9000;

let myIp = "192.168.10.191";

// let userIpUdp = "192.168.10.50";

// 广播Ip
let broadcastIp = "255.255.255.255";

const readline = require("node:readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

// function setMessage() {
//   rl.question("", (v) => {
//     let message = v;
//     server.send(message, prot, broadcastIp);
//     setMessage();
//   });
// }

// setMessage();

server.bind(prot, () => {
  server.setBroadcast(true);
});
